﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LifeController : MonoBehaviour 
{	
	public int health;
	[HideInInspector] public Skills skills;
	[HideInInspector]public Skill healthSkill;
	public Collider col;
	[HideInInspector]private MotionController controller;
	[HideInInspector] public Inventory inventory;
	private PhotonView photView;
	[HideInInspector]public SpawnManager spawnManager;
	[HideInInspector]public GameObject lifeCam;
	public GameObject avatar;
	public GameObject deadAvatarPrefab;
	[HideInInspector]public TeamAble teamAble;

	private HealthBarController hbc;
	public characterType type;
	public Transform deadAvatarTransform;
	[HideInInspector]public bool isDead = false;
	private NPCSpawn npcSpawn;
	public enum characterType
	{	
		homeBase,
		player,
		turret,
		npc,
	}

	void Awake()
	{	
		inventory = GetComponent<Inventory>();
		controller = this.GetComponent<MotionController>();
		skills = this.GetComponent<Skills> ();
		teamAble = this.GetComponent<TeamAble>();
		photView = PhotonView.Get (this);
		hbc = this.GetComponent<HealthBarController>();
		hbc.avatar = avatar;
		npcSpawn = GetComponent<NPCSpawn>();
		foreach (Skill skill in skills.skills)
		{
			if (skill.skillName == (int)GameConstants.SkillType.health)
			{
				healthSkill = skill;
				break;
			}
		}
		controller = this.GetComponent<MotionController> ();
		if (col == null)
		{
			col = this.GetComponent<Collider> ();
		}
		if (deadAvatarTransform == null)
		{
			deadAvatarTransform = avatar.transform;
		}
	}
	void Start()
	{	
		spawnManager = GameManager.instance.spawnManager;
		health = healthSkill.level;
	}

	public void TakeDamage(int amount, int attackerID)
	{	
		PhotonPlayer owner = photView.owner;
		if (photView.isSceneView)
		{
			owner = PhotonNetwork.masterClient;
		}
			photView.RPC("RPCDamageOwner",owner, amount, attackerID);
	}

	[PunRPC]
	public void RPCDamageOwner(int amount, int  attackerID, PhotonMessageInfo info)
	{	
		if (health>0 && !isDead)
		{
			if (amount>health)
			{
				amount = health;
			}
				health -= amount;
			if (LocalIsOwner())
			{	
				LifeController damager = PhotonView.Find(attackerID).GetComponent<LifeController>();
				if (damager != null && type!=characterType.player)
				{	
					controller.Attack (damager);	
				}
				if (health <= 0)
				{	
					Die ();
				}
				photView.RPC("RPCDamageAll",PhotonTargets.All,amount,HealthPercent());
			}
			
		}
	}
	public bool LocalIsOwner()
	{
		return (photView.isMine || (photView.isSceneView && PhotonNetwork.isMasterClient));
	}
	[PunRPC]
	public void RPCDamageAll(int amount,float healthPercent)
	{	
		
		MakeUIEffects(amount,healthPercent);	
	} 
	float HealthPercent()
	{
		float percent = (float)health/(float)healthSkill.level;
		percent = Mathf.Clamp(percent,0,1);
		return percent;
	}

	[PunRPC]
	public void MakeUIEffects(int damage,float healthPercent)
	{
		BringUpHealthBar(healthPercent);
		hbc.HitSplat(damage);
	}
	
	public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
	{
		if (LocalIsOwner() && stream.isWriting)
		{
			stream.SendNext(health);
			stream.SendNext(isDead);
		}
		if (!LocalIsOwner() && stream.isReading)
		{
			health = (int)stream.ReceiveNext();
			isDead = (bool)stream.ReceiveNext();
		}
	}

	public void Die()
	{
		if (LocalIsOwner())
		{	
			isDead = true;
			controller.GoTo(transform.position);
			if (inventory!=null)
			{
				inventory.DropAll();
			}
			photView.RPC ("RPCDie", PhotonTargets.All);
			
			
			switch (type)
			{
				case characterType.player:
				{	
					transform.position = GameManager.instance.spawnManager.spawnPoint.position;
					controller.GoTo(transform.position);
					GetComponent<LowResPositionSync>().SendPosition();
					GameManager.instance.spawnManager.Die();
					break;
				}
				case characterType.homeBase:
				{	
					spawnManager.BaseDeath(teamAble.team);
					break;
				}
				case characterType.npc:
				{	
					if (npcSpawn!= null)
					{
						npcSpawn.Die();
					}
					break;
				}

			}
			
		}
		
	}
	public void Respawn()
	{	
		if (LocalIsOwner())
		{	
			health = healthSkill.level;
			photView.RPC ("RPCRespawn", PhotonTargets.All);
		}
	}

	[PunRPC]
	public void RPCDie()
	{	
		InstantiateDead();
		avatar.SetActive(false);
	}
	public void OnJoinedRoom()
	{
		StartCoroutine(WaitThenCheckDeath());
	}

	IEnumerator WaitThenCheckDeath()
	{
		yield return new WaitForSeconds(1);
		if (isDead)
		{
			isDead = true;
			avatar.SetActive(false);
		}
	}
	[PunRPC]
	public void RPCRespawn()
	{	
		avatar.SetActive(true);
		hbc.avatar = avatar;
		isDead = false;
	}
	void InstantiateDead()
	{
		GameObject deadAvatar =  GameObject.Instantiate(deadAvatarPrefab,deadAvatarTransform.position,deadAvatarTransform.rotation);
		hbc.CloseTo(deadAvatar);
	}

	void BringUpHealthBar(float healthPercent)
	{
		hbc.SetHealth(healthPercent);
	}
}
